import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { createMatch, getMatchDetail, updateMatch, type Match } from '@/api/matches'
// 表单引用
export const formRef = ref()
export const submitting = ref(false)

// 编辑模式
export const isEditMode = ref(false)
export const matchId = ref<number | null>(null)

// 表单数据
export const form = reactive<Omit<Match, 'id' | 'created_at' | 'updated_at'>>({
  tournament_name: '',
  tournament_type: 'WTT常规赛',
  tournament_score: 0,
  tournament_intro: '',
  venue: '',
  match_time: '',
  status: 'pending',
  remarks: ''
})

// 表单验证规则
export const rules = {
  tournament_name: [
    { required: true, message: '请输入赛事名称', trigger: 'blur' }
  ],
  tournament_type: [
    { required: true, message: '请选择赛事类型', trigger: 'change' }
  ],
  tournament_score: [
    { required: true, message: '请输入赛事积分', trigger: 'blur' }
  ],
  tournament_intro: [
    { required: true, message: '请输入赛事简介', trigger: 'blur' }
  ],
  venue: [
    { required: true, message: '请输入赛事地点', trigger: 'blur' }
  ],
  match_time: [
    { required: true, message: '请选择比赛时间', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择比赛状态', trigger: 'change' }
  ],
  remarks: [
    { required: true, message: '请输入备注', trigger: 'blur' }
  ]
}

// 方法
export const goBack = (router: any) => {
  router.push('/matches/list')
}

// 取消功能 - 带确认对话框
export const handleCancel = async (router: any) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消吗？未保存的数据将丢失。',
      '取消确认',
      {
        confirmButtonText: '确定取消',
        cancelButtonText: '继续编辑',
        type: 'warning'
      }
    )
    goBack(router)
  } catch (error) {
    // 用户点击了"继续编辑"，不做任何操作
  }
}

export const handleSubmit = async (router: any) => {
  if (!formRef.value) return
  
  try {
    // 验证表单
    await formRef.value.validate()
    submitting.value = true
    
    let response
    if (isEditMode.value && matchId.value) {
      // 更新赛事
      response = await updateMatch(matchId.value, form)
      if (response.success) {
        ElMessage.success('赛事更新成功！')
        // 延迟跳转，让用户看到成功提示
        setTimeout(() => {
          router.push('/matches/list?refresh=true')
        }, 1000)
      } else {
        ElMessage.error(response.message || '更新赛事失败')
      }
    } else {
      // 创建赛事
      response = await createMatch(form)
      if (response.success) {
        ElMessage.success('赛事添加成功！')
        // 延迟跳转，让用户看到成功提示
        setTimeout(() => {
          router.push('/matches/list?refresh=true')
        }, 1000)
      } else {
        ElMessage.error(response.message || '添加赛事失败')
      }
    }
  } catch (error: any) {
    console.error(isEditMode.value ? '更新赛事失败:' : '添加赛事失败:', error)
    
    // 处理验证错误
    if (error.message && error.message.includes('validation')) {
      ElMessage.warning('请检查表单填写是否正确')
    } else {
      ElMessage.error(isEditMode.value ? '更新赛事失败，请重试' : '添加赛事失败，请重试')
    }
  } finally {
    submitting.value = false
  }
}

export const handleReset = () => {
  if (!formRef.value) return
  
  // 重置表单字段
  formRef.value.resetFields()
  
  // 重置表单数据到初始状态
  Object.assign(form, {
    tournament_name: '',
    tournament_type: '常规赛',
    tournament_score: 0,
    tournament_intro: '',
    venue: '',
    match_time: '',
    status: 'pending',
    remarks: ''
  })
  
  ElMessage.info('表单已重置')
}

// 初始化函数
export const initPage = async (route: any) => {
  const { id, mode } = route.query
  
  if (id && mode === 'edit') {
    isEditMode.value = true
    matchId.value = Number(id)
    
    try {
      const response = await getMatchDetail(Number(id))
      if (response.success && response.data) {
        Object.assign(form, {
          tournament_name: response.data.tournament_name,
          tournament_type: response.data.tournament_type,
          tournament_score: response.data.tournament_score,
          tournament_intro: response.data.tournament_intro,
          venue: response.data.venue,
          match_time: response.data.match_time,
          status: response.data.status,
          remarks: response.data.remarks
        })
      }
    } catch (error) {
      console.error('获取赛事详情失败:', error)
      ElMessage.error('获取赛事详情失败')
    }
  }
}

